/*
 * Project: book
 * 
 * File Created at 2017年9月14日
 * 
 * Copyright 2016 CMCC Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ZYHY Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package com.whb.book.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.whb.book.common.ActionResponse;
import com.whb.book.common.Constants;
import com.whb.book.common.ResMsg;
import com.whb.book.common.util.DateUtil;
import com.whb.book.common.util.MsisdnUtil;
import com.whb.book.dto.SyncUserVO;
import com.whb.book.service.BookService;


/**
 * @Type SyncAction.java
 * @Desc 同步方法是 n个用户都借阅了同一本书，txt文件里放着用户的信息，在该书的页面里导入txt文件
 * ，让数据写入 user表，UserBookRelation表
 * @author wanghb
 * @date 2017年9月14日 下午9:32:57
 * @version 
 */
public class SyncAction {
    
    private static Logger logger = LoggerFactory.getLogger(SyncAction.class);
    
    @Autowired
    private BookService bookService;
    
    @RequestMapping(value = "/syncFile", method = RequestMethod.POST, produces = { "text/plain;charset=UTF-8" })
    @ResponseBody
    public String syncFile(@RequestParam("userFile") MultipartFile file,HttpServletRequest request,
                           HttpServletResponse response, ModelMap modelMap){
        logger.info("=================学生借阅书籍同步=================");
        ActionResponse ar = new ActionResponse();
        String bookId = request.getParameter("bookId");
        String fileName = file.getOriginalFilename();
        if(StringUtils.isNotBlank(fileName)){
            fileName = fileName.trim();
            if(!fileName.endsWith(".txt") && !fileName.endsWith(".TXT")){
                logger.error("上传文件错误 {}", fileName);
                ar.setStatusAndMessage(ResMsg.FILE_ERROR.getCode(),
                        ResMsg.FILE_ERROR.getMsg());
                return JSON.toJSONString(ar);
            }
        }
        List<SyncUserVO> list = new ArrayList<SyncUserVO>();
        try(BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream(), "GBK"))) {
            String line = br.readLine();
            while(StringUtils.isNotBlank(line)){
                String[] temp = line.split("\\|", -1);
                if (temp.length != 12) {
                    ar.setStatusAndMessage(ResMsg.FILE_ERROR.getCode(),
                            ResMsg.FILE_ERROR.getMsg());
                    return JSON.toJSONString(ar);
                }else{
                    logger.info("文件格式正确，解析文件");
                    SyncUserVO suvo = new SyncUserVO();
                    try {
                        suvo.setStaffId(temp[0]);
                        suvo.setUsername(temp[1]);
                        String gender = temp[2];
                        if (StringUtils.isNotEmpty(gender)) {
                            if (!Constants.GENDER_FEMALE.equals(gender)
                                    && !Constants.GENDER_MALE.equals(gender)) {
                                ar.setStatusAndMessage(ResMsg.GENDER_ERROR.getCode(),
                                        ResMsg.GENDER_ERROR.getMsg());
                                return JSON.toJSONString(ar);
                            }
                        }
                        suvo.setGender(temp[2]);
                        suvo.setBirth(StringUtils.isNotBlank(temp[3]) ? DateUtil.s2d(temp[3],
                                DateUtil.YYYYMMDD) : DateUtil.s2d("19700101", DateUtil.YYYYMMDD));
                        if (!MsisdnUtil.isMsisdn(temp[4])) {
                            ar.setStatusAndMessage(ResMsg.MSISDN_ERROR.getCode(),
                                    ResMsg.MSISDN_ERROR.getMsg());
                            return JSON.toJSONString(ar);
                        }
                        suvo.setMsisdn(temp[4]);
                        suvo.setEmail(temp[5]);
                        suvo.setHometown(temp[6]);
                        suvo.setEntryTime(DateUtil.s2d(temp[7],
                                DateUtil.YYYYMMDD));
                        suvo.setCollege(temp[8]);
                        suvo.setMajor(temp[9]);
                        suvo.setGrade(temp[10]);
                        suvo.setBorrowStatus(StringUtils.isNotEmpty(temp[11]) ? Integer
                                .parseInt(temp[11]) : 0);
                        list.add(suvo);
                    } catch (Exception e) {
                        logger.error("文件内容解析出错", e);
                        ar.setStatusAndMessage(ResMsg.FILE_ERROR.getCode(),
                                ResMsg.FILE_ERROR.getMsg());
                        return JSON.toJSONString(ar);
                    }
                }
                line = br.readLine();
            }
            list = new ArrayList<SyncUserVO>(new HashSet<SyncUserVO>(list));
            bookService.syncFile(list, Long.valueOf(bookId));
            ar.setStatusAndMessage(ResMsg.SUCCESS.getCode(), ResMsg.SUCCESS.getMsg());
        } catch (IOException e) {
            logger.error("学生借阅书籍信息同步错误", e);
        }
        return JSON.toJSONString(ar);
    }
}


/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年9月14日 wanghb create
 */